package com.springboot.common.handler;

import com.springboot.common.annotation.SQLDate;
import com.springboot.common.util.DateUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;


/**
 * @SQLDate 时间字段默认赋值处理类  基于AOP
 */
@Aspect
@Component
public class SQLDateHandler {
    private static final Logger logger = LoggerFactory.getLogger(SQLDateHandler.class);

    @Pointcut(value = "execution(* com.springboot..*Controller.*(..))")
    public void webLog() {
    }

    @Before(value = "webLog()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        /*logger.info("joinPoint==={}",joinPoint);
        logger.info("joinPoint.getArgs()==={}",joinPoint.getArgs());
        logger.info("joinPoint.getKind()==={}",joinPoint.getKind());
        logger.info("joinPoint.getSignature()==={}",joinPoint.getSignature());
        logger.info("joinPoint.getThis()==={}",joinPoint.getThis());
        logger.info("joinPoint.getTarget()==={}",joinPoint.getTarget());
        logger.info("joinPoint.getStaticPart()==={}",joinPoint.getStaticPart());*/

        Arrays.asList(joinPoint.getArgs()).stream()
                .filter(o -> o != null)
                .forEach(o -> {
                    Arrays.asList(o.getClass().getDeclaredFields()).stream().forEach(e -> {
                        SQLDate declaredAnnotation = e.getDeclaredAnnotation(SQLDate.class);
                        if (declaredAnnotation == null) return;
                        ReflectionUtils.makeAccessible(e);
                        ReflectionUtils.setField(e, o, DateUtils.now());
                    });
                });
    }


}
